import logging
import time

from app.models import data_treating

re_data_map = {
    'ent_name': 'entName',  # 企业名称
    'unisc_id': 'uniscId',  # 社会信用代码
    'reg_no': 'regNo',  # 注册号
    'name': 'name',  # 法定代表人，
    'reg_org_cn': 'regOrg_CN',  # 登记机关
    'dom': 'dom',  # 企业地址
    'est_date': 'estDate',  # 成立时间
    'ent_type_cn': 'entType_CN',  # 公司类型
    'reg_cap': 'regCap',  # 注册资本
    'reg_state_cn': 'regState_CN',  # 登记状态
    'op_scope': 'opScope',  # 经营范围
    'op_to': 'opTo',  # 营业时间至
    'op_from': 'opFrom'  # 营业时间起
}


def data_treat(data):
    all_data = []
    if data:
        if 'details_data' in data.keys() and data['details_data']:
            a = 0
            for i in data['details_data']:
                re_data = {}
                logging.info(f"企业工商信息_{a}：{i}")
                try:
                    for key, value in re_data_map.items():
                        if value == 'regCap':
                            if 'regCap' in i.keys() and i["regCap"] != '元整':
                                re_data[key] = i[value] + i['regCapCurCN'] if i[value] is not None else '0'
                            else:
                                re_data[key] = ''
                        else:
                            if value not in i['result'].keys() and value == 'entName':
                                re_data[key] = i['result']['traName'] if i['result']['traName'] is not None else ''
                            elif value not in i['result'].keys() and value == 'dom':
                                re_data[key] = i['result']['opLoc'] if i['result']['opLoc'] is not None else ''
                            elif value not in i['result'].keys():
                                logging.error(f'返回的result数据无key值：{value}')
                                re_data[key] = ''
                            else:
                                re_data[key] = i['result'][value] if i['result'][value] is not None else ''
                    re_data['updata_data'] = int(time.time())
                    all_data.append(re_data)
                    data_treating(re_data)
                except Exception as e:
                    logging.error(e, exc_info=True)
                a = a + 1
        else:
            all_data = data
    else:
        all_data = data
    logging.info(f'返回的all_data数据是：{all_data}')
    return all_data
